﻿using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Metadata.Dao;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.Metadata.SPI;
using T.ServiceComponent.Error;

namespace T.FAS.Runtime.Metadata.Service
{
    /// <summary>
    /// 元数据管理器工厂类
    /// </summary>
    public class MetaDataManagerFactory
    {
        public static IMetaDataManager CreateMetaDataManager(string metadataType)
        {
            if (string.IsNullOrWhiteSpace(metadataType))
                throw new ArgumentNullException("MetaDataManagerFactory.CreateMetaDataManager.metadataType");
            var config = MetaTypeCacheService.Get(metadataType);
            if (string.IsNullOrWhiteSpace(config.MetaDataManagerType))
            {
                return null;
            }
            return CreateInstance<IMetaDataManager>(config.MetaDataManagerType);
        }
        public static IMetaDataSerializer CreateMetadataSerializer(string metadataType)
        {
            if (string.IsNullOrWhiteSpace(metadataType))
                throw new ArgumentNullException("MetaDataManagerFactory.CreateMetadataSerializer.metadataType");
            var config = MetaTypeCacheService.Get(metadataType);
            if (string.IsNullOrWhiteSpace(config.MetadataSerializer))
            {
                return null;
            }
            return CreateInstance<IMetaDataSerializer>(config.MetadataSerializer);
        }

        public static IExtMetaDataManager CreateExtMetaDataManager(string metadataType)
        {
            if (string.IsNullOrWhiteSpace(metadataType))
                throw new ArgumentNullException("MetaDataManagerFactory.CreateExtMetaDataManager.metadataType");
            var config = MetaTypeCacheService.Get(metadataType);
            if (string.IsNullOrWhiteSpace(config.MetaDataExtManagerType))
            {
                return null;
            }
            return CreateInstance<IExtMetaDataManager>(config.MetaDataExtManagerType);

        }


        private static T CreateInstance<T>(string type)
        {
            object instance = null;
            try
            {
                instance = Activator.CreateInstance(Type.GetType(type));
                if (instance == null)
                {
                    throw new Exception(string.Format(MetaDataExceptionCode.ReflectMetaDataMgrExceptionMessage, type));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format(MetaDataExceptionCode.ReflectMetaDataMgrExceptionMessage, type), ex);
            }

            return (T)instance;
        }
    }
}
